<?php

class Info extends Api
{
    public function edit()
    {
        $id   = $this->getParam('id');
        $name = $this->getParam('name');
        $this->getDb()->where("id", $id);
        if (!$this->isAdmin) {
            $this->getDb()->where("pid", $this->userInfo['role']);
        }
        $info = $this->getDb()->getOne('infos');
        if (empty($info)) {
            $this->backJson([], ApiConst::BACK_NOT_EXIST_INFO);
        }
        $data = [];
        if ($name) {
            $data['name'] = $name;
        }
        $this->getDb()->where('id', $id);
        if (!$this->isAdmin) {
            $this->getDb()->where("pid", $this->userInfo['role']);
        }
        if ($this->getDb()->update('infos', $data)) {
            $this->backJson([]);
        }
        $this->backJson([], ApiConst::BACK_CODE_ERROR);
    }

    public function list()
    {
        $page     = (int)$this->getParam('page', 1);
        $pageSize = (int)$this->getParam('pageSize', 10);
        $page_type = $this->getParam('page_type', '');
        //$pageSize = 30;
        $limit_time = 0;
        if ($page_type == 'receive') {
            $this->getDb()->where('id', $this->userInfo['id']);
            $userInfo = $this->getDb()->getOne('users', 'id,time');
            if (($userInfo['time'] - time()) > 0 && ($userInfo['time'] - time()) < 5) {
                $limit_time = $userInfo['time'] - 5;
            }
        }

        $search_id           = $this->getParam('id', '');
        $search_phone        = $this->getParam('phone', '');
        $search_u_id         = $this->getParam('u_id', '');
        $search_state        = $this->getParam('state', '');
        $search_source       = $this->getParam('source', '');
        $search_search       = $this->getParam('search', '');
        $search_source_type  = $this->getParam('source_type', '');
        $search_created_at      = $this->getParam('created_at', '');
        if ($search_id !== '') {
            $this->getDb()->where('id', $search_id);
        }
        if ($search_phone !== '') {
            $this->getDb()->where('phone', '%' . $search_phone . '%', 'like');
        }
        if ($search_search !== '') {
            $this->getDb()->where('search', '%' . $search_search . '%', 'like');
        }
        if (!empty($search_u_id)) {
            $this->getDb()->where('u_id', $search_u_id, 'in');
        }
        if (!empty($search_state)) {
            $this->getDb()->where('state', $search_state, 'in');
        }
        if (!empty($search_source)) {
            $this->getDb()->where('source', $search_source, 'in');
        }
        if (!empty($search_source_type)) {
            $this->getDb()->where('source_type', $search_source_type, '=');
        }
        if (empty($search_created_at)) {
            $search_created_at_s = '';
            $search_created_at_e = '';
        } else {
            $search_created_at_s = $search_created_at[0];
            $search_created_at_e = $search_created_at[1];
        }
        if ($search_created_at_s !== '') {
            $start_t = strtotime(date('Y-m-d', strtotime($search_created_at_s)));
        }
        if ($search_created_at_e !== '') {
            $end_t = strtotime(date('Y-m-d', strtotime("+1 day", strtotime($search_created_at_e))));
        }
        if ($search_created_at_s !== '' && $search_created_at_e !== '') {
            $where = [$start_t, $end_t];
            $this->getDb()->where("created_at", $where,'between');
        } else if ($search_created_at_s !== '' && $search_created_at_e === '') {
            $this->getDb()->where("created_at", $start_t, '>=');
        } else if ($search_created_at_s === '' && $search_created_at_e !== '') {
            $this->getDb()->where("created_at", $end_t, '<=');
        }
        if ($page_type == 'receive') {
            if ($limit_time > 0) {
                $this->getDb()->where("created_at", $limit_time, "<=");
            }
            $this->getDb()->where("u_id", 0);
        } else {
            if ($page_type == 'info' || $page_type == 'shared') {
                $this->getDb()->where("type", $page_type == 'shared' ? 1 : 0);
            }
            if ($page_type != 'shared') {
                if ($this->userInfo['pid'] != 1) {
                    $this->getDb()->where("u_id", $this->userInfo['id']);
                } else {
                    if ($page_type != 'info') {

                    } else {
                        $this->getDb()->where("u_pid", $this->userInfo['id']);
                    }
                }
            }
        }
        $this->getDb()->pageLimit = $pageSize;

        if ($page_type == 'receive' || $page_type == '') {
            $this->getDb()->orderBy('id', 'DESC');
        } else {
            $this->getDb()->orderBy('update_at', 'DESC');
        }

        $list = $this->getDb()->paginate("infos", $page, 'id,type,phone,brand,search,path,path_f,u_pid,u_id,source,source_type,state,ip,address_ip,address_phone,created_at,update_at');
        $uids = array_unique(array_column($list, 'u_id'));
        $total = $this->getDb()->totalCount;
        if (count($uids) > 0) {
            $this->getDb()->where('id', $uids, 'in');
            $userInfos = $this->getDb()->get('users', null, 'id,nick');
            $userInfos = array_column($userInfos, null, 'id');
        }
        foreach ($list as $k => $item) {
            $list[$k]['created_at'] = date('Y-m-d H:i:s', $item['created_at']);
            $list[$k]['update_at']  = date('Y-m-d H:i:s', $item['update_at']);
            $list[$k]['u_nick']  = $userInfos[$item['u_id']]['nick'];
            $list[$k]['state'] = CrmConst::STATE[$item['state']];
            $list[$k]['source_type'] = $item['source_type'];
            $list[$k]['source_type_name'] = CrmConst::SOURCE_TYPE[$item['source_type']];
            $list[$k]['source_name'] = CrmConst::SOURCE[$item['source']];
            $list[$k]["receive_btn"] = 0;
            if (in_array($page_type, ['receive', 'shared']) && $this->userInfo['pid'] > 1 && $this->userInfo['id'] != $item['u_id']) {
                $list[$k]['phone'] = substr($item['phone'], 0, 3) . '****' . substr($item['phone'], 7);
                $list[$k]["address_ip"] = "**-**";
                $list[$k]["address_phone"] = "**-**";
                $list[$k]["brand"] = "***";
                $list[$k]["ip"] = "***";
                $list[$k]["path"] = "***";
                $list[$k]["path_f"] = "***";
                $list[$k]["search"] = "***";
                $list[$k]["source"] = 0;
                $list[$k]["source_name"] = "***";
                $list[$k]["source_type"] = "***";
                $list[$k]["state"] = "";
                $list[$k]["type"] = 0;
                $list[$k]["u_id"] = 0;
                $list[$k]["u_nick"] = null;
                $list[$k]["u_pid"] = 0;
                $list[$k]["receive_btn"] = 1;
            }
        }

        $this->backJson([
            'list'      => $list,
            'total'     => (int)$total,
            'page'      => (int)$page,
            'totalPage' => (int)ceil($total / $pageSize),
            'pageSize'  => (int)$pageSize
        ]);
    }


    public function state()
    {
        $id     = (int)$this->getParam('id', 0);
        $state = (int)$this->getParam('state');
        $this->getDb()->where("id", $id);
        $info = $this->getDb()->getOne('infos', 'id,type,u_id,state');
        if ($info['u_id'] != $this->userInfo['id']) {
            $this->backJson([], ApiConst::BACK_INFO_LOSE_SELF);
        }
        if ($info['type'] != 0) {
            $this->backJson([], ApiConst::BACK_NOT_EXIST_INFO);
        }
        if ($info['state'] == $state) {
            $this->backJson([]);
        }
        $this->getDb()->where("id", $id);
        $this->getDb()->update('infos', ['state' => $state]);
        $this->backJson([]);
    }


    public function remark()
    {
        $id     = (int)$this->getParam('id', 0);
        $remark = $this->getParam('remark');
        $this->getDb()->where("id", $id);
        $info = $this->getDb()->getOne('infos', 'id,type,u_id,remark');
        if ($info['u_id'] != $this->userInfo['id']) {
            $this->backJson([], ApiConst::BACK_INFO_LOSE_SELF);
        }
        if ($info['type'] != 0) {
            $this->backJson([], ApiConst::BACK_NOT_EXIST_INFO);
        }
        if ($info['remark'] == $remark) {
            $this->backJson([]);
        }
        $this->getDb()->where("id", $id);
        $this->getDb()->update('infos', ['remark' => $remark]);
        $this->backJson([]);
    }

    public function receive()
    {
        if ($this->isAdmin || $this->userInfo['pid'] == 1) {
            $this->backJson([], ApiConst::BACK_INFO_NO_RECEIVE);
        }
        $id = (int)$this->getParam('id', 0);
        if ($id <= 0 || !is_numeric($id)) {
            $this->backJson([], ApiConst::BACK_PARAM_ERROR);
        }
        $this->getDb()->where("id", $this->userInfo['id']);
        $userInfo = $this->getDb()->getOne('users', 'id,time,num,max_num');
        if (empty($userInfo)) {
            $this->backJson([], ApiConst::BACK_NOT_EXIST_USER_NANE);
        }
        if ($userInfo['time'] != strtotime(date('Y-m-d'))) {
            $this->getDb()->where("id", $this->userInfo['id']);
            $this->getDb()->update('users', [
                'time' => strtotime(date('Y-m-d')),
                'num' => 0,
            ]);
            $userInfo['num'] = 0;
            //var_dump(2222);
        }
        if ($userInfo['num'] >= $userInfo['max_num']) {
            $this->backJson([], ApiConst::BACK_INFO_RECEIVE_LIMIT, "今天领取已上限（一天只能领取{$userInfo['max_num']}条，0点重置）");
        }
        $this->getDb()->where("id", $id);
        $info = $this->getDb()->getOne('infos', 'id,u_id,u_pid,type');
        if ($info['u_id'] > 0 && $info['type'] == 0) {
            $this->backJson([], ApiConst::BACK_INFO_RECEUVED);
        }
        $this->getDb()->where("id", $id);
        if ($info['type'] == 0) {
            $this->getDb()->where("u_id", 0);
        }
        $res = $this->getDb()->update('infos', [
            'u_id' => $this->userInfo['id'],
            'u_pid' => $this->userInfo['pid'],
            'update_at' => time(),
            'type' => 0
        ]);
        if ($res) {
            $this->getDb()->where("id", $this->userInfo['id']);
            $this->getDb()->update('users', [
                'num' => $userInfo['num'] + 1,
            ]);
            $this->backJson([]);
        }
        $this->backJson([], ApiConst::BACK_CODE_ERROR);
    }


    public function lose()
    {
        $id = (int)$this->getParam('id', 0);
        if ($id <= 0 || !is_numeric($id)) {
            $this->backJson([], ApiConst::BACK_PARAM_ERROR);
        }
        $this->getDb()->where("id", $id);
        $info = $this->getDb()->getOne('infos', 'id,u_id,u_pid');
        if ($info['u_id'] > 0 && $this->userInfo['id'] == $info['u_id']) {

        } else {
            $this->backJson([], ApiConst::BACK_INFO_LOSE_SELF);
        }

        $this->getDb()->where("id", $id);
        $this->getDb()->where("u_id", $this->userInfo['id']);
        $res = $this->getDb()->update('infos', [
            'type' => 1,
            'update_at' => time()
        ]);
        if ($res) {
            $this->backJson([]);
        }
        $this->backJson([], ApiConst::BACK_CODE_ERROR);
    }

    public function detail()
    {
        $id = (int)$this->getParam('id', 0);
        if ($id <= 0 || !is_numeric($id)) {
            $this->backJson([], ApiConst::BACK_PARAM_ERROR);
        }
        $this->getDb()->where("id", $id);
        $info = $this->getDb()->getOne('infos', 'id,type,phone,brand,search,path,path_f,u_pid,u_id,source,source_type,state,remark,created_at,update_at');

        if ($info['u_id'] > 0 && ($info['u_id'] == $this->userInfo['id'] || $this->isAdmin || $this->userInfo['id'] == $info['u_pid'])) {
            $data = [
                'id' => $info['id'],
                'type' => $info['type'],
                'phone' => $info['phone'],
                'brand' => $info['brand'],
                'path' => $info['path'],
                'path_f' => $info['path_f'],
                'source' => $info['source'],
                'source_type' => $info['source_type'],
                'source_type_name' => CrmConst::SOURCE_TYPE[$info['source_type']],
                'source_name' => CrmConst::SOURCE[$info['source']],
                'state' => $info['state'],
                'state_name' => CrmConst::STATE[$info['state']],
                'search' => $info['search'],
                'remark' => $info['remark'],
                'created_at' => date('Y-m-d H:i:s', $info['created_at']),
                'update_at' => date('Y-m-d H:i:s', $info['update_at']),
            ];
            $this->getDb()->where('id', $info['u_id']);
            $userInfo = $this->getDb()->getOne('users', 'name,nick');
            $data['u_name'] = $userInfo['name'];
            $data['u_nick'] = $userInfo['nick'];


            if ($this->isAdmin || $this->userInfo['id'] == $info['u_pid']) {
                $file = 1;
            } else {
                $this->getDb()->where("id", $this->userInfo['role']);
                $role = $this->getDb()->getOne('roles');
                $roles = explode(',', $role['roles']);
                $file = in_array(7, $roles) ? 1 : 0;
            }
            $data['file'] =$file;
        } else {
            $data = [
                'id' => $info['id'],
                'type' => $info['type'],
                'phone' => substr($info['phone'], 0, 3) . '****' . substr($info['phone'], 7),
                'brand' => '***',
                'path' => '***',
                'path_f' => '***',
                'source' => '***',
                'source_name' => '***',
                'source_type' => '***',
                'state' => '***',
                'search' => '***',
                'remark' => '***',
            ];
            $data['u_name'] = '***';
            $data['u_nick'] = '***';
        }

        $this->backJson(['detail' => $data]);
    }

    public function statistics()
    {
        $data = [];
        $this->getDb()->where('u_id', $this->userInfo['id']);
        $this->getDb()->where('type', 0);
        $infos = $this->getDb()->getOne('infos', 'count(id) as nums');
        $data['people'] = $infos['nums'];

        $this->getDb()->where('u_id', $this->userInfo['id']);
        $this->getDb()->where('type', 1);
        $infos = $this->getDb()->getOne('infos', 'count(id) as nums');
        $data['people_lose'] = $infos['nums'];

        $this->getDb()->where('u_id', $this->userInfo['id']);
        $this->getDb()->where('update_at', strtotime(date('Y-m-d')), '>=');
        $this->getDb()->where('type', 0);
        $infos = $this->getDb()->getOne('infos', 'count(id) as nums');
        $data['people_today'] = $infos['nums'];


        $this->getDb()->where('u_id', $this->userInfo['id']);
        $this->getDb()->where('update_at', strtotime(date('Y-m-d')) , '>=');
        $this->getDb()->where('type', 1);
        $infos = $this->getDb()->getOne('infos', 'count(id) as nums');
        $data['people_lose_today'] = $infos['nums'];

        $this->backJson($data);
    }

    public function info_statistics()
    {
        $infos1 = $this->getDb()->query("select count(id) as nums, u_id from crm_infos where type=0 and  update_at>=".strtotime(date('Y-m-d'))." and u_pid=" . $this->userInfo['id'] . ' group by u_id');
        $uids1 = array_column($infos1, 'u_id');
        $infos2 = $this->getDb()->query("select count(id) as nums, u_id from crm_infos where type=1 and  update_at>=".strtotime(date('Y-m-d'))." and u_pid=" . $this->userInfo['id'] . ' group by u_id');
        $uids2 = array_column($infos2, 'u_id');
        $uids = array_merge($uids1,$uids2);
        $uids = array_unique($uids);
        if (count($uids) > 0) {
            $this->getDb()->where('id',$uids, 'in');
            $userInfo = $this->getDb()->get('users');
            $userInfo = array_column($userInfo, null, 'id');
        }
        foreach ($infos1 as $k => $value) {
            $infos1[$k]['name'] = $userInfo[$value['u_id']]['name'];
            $infos1[$k]['nick'] = $userInfo[$value['u_id']]['nick'];
        }
        foreach ($infos2 as $k => $value) {
            $infos2[$k]['name'] = $userInfo[$value['u_id']]['name'];
            $infos2[$k]['nick'] = $userInfo[$value['u_id']]['nick'];
        }
        $data = [
            'people_today' => $infos1,
            'people_lose_today' => $infos2,
        ];

        $infos1 = $this->getDb()->query("select count(id) as nums, u_id from crm_infos where type=0 and u_pid=" . $this->userInfo['id'] . ' group by u_id');
        $uids1 = array_column($infos1, 'u_id');
        $infos2 = $this->getDb()->query("select count(id) as nums, u_id from crm_infos where type=1 and u_pid=" . $this->userInfo['id'] . ' group by u_id');
        $uids2 = array_column($infos2, 'u_id');
        $uids = array_merge($uids1,$uids2);
        $uids = array_unique($uids);
        if (count($uids) > 0) {
            $this->getDb()->where('id',$uids, 'in');
            $userInfo = $this->getDb()->get('users');
            $userName = array_column($userInfo, 'nick');
            $userInfo = array_column($userInfo, null, 'id');
        }

        foreach ($infos1 as $k => $value) {
            $infos1[$k]['name'] = $userInfo[$value['u_id']]['name'];
            $infos1[$k]['nick'] = $userInfo[$value['u_id']]['nick'];
        }
        foreach ($infos2 as $k => $value) {
            $infos2[$k]['name'] = $userInfo[$value['u_id']]['name'];
            $infos2[$k]['nick'] = $userInfo[$value['u_id']]['nick'];
        }

        $data['people'] = $infos1;
        $data['people_lose'] = $infos2;
        $data['user_name'] = $userName;
        $this->backJson($data);
    }

    public function config()
    {
        $userInfos = [];
        $uid = [];
        if ($this->userInfo['pid'] == 1) {
            $this->getDb()->where('u_pid', $this->userInfo['id']);
            $this->getDb()->groupBy('u_id');
            $infos = $this->getDb()->get('infos', null, 'u_id');
            $uids = array_column($infos, 'u_id');
            if (count($uids) > 0) {
                $this->getDb()->where('id', $uids, 'in');
                $userInfos = $this->getDb()->get('users', null, 'id,nick');
                $uid = [];
                foreach ($userInfos as $item) {
                    $uid[] = ['value' => $item['id'], 'label' => $item['nick']];
                }
            }
        }
        $source_type = [];
        $source_type[] = ['value' => '','label' => '全部'];
        foreach (CrmConst::SOURCE_TYPE as $k => $value) {
            $source_type[] = ['value' => $k,'label' => $value];
        }
        $source = [];
        foreach (CrmConst::SOURCE as $k => $value) {
            if ($value == '') {
                continue;
            }
            $source[] = ['value' => $k,'label' => $value];
        }
        $state = [];
        foreach (CrmConst::STATE as $k => $value) {
            if ($value == '') {
                continue;
            }
            $state[] = ['value' => $k,'label' => $value];
        }
        $data = [
            'source_type' => $source_type,
            'source' => $source,
            'state' => $state,
            'u_id' => $uid
        ];
        $this->backJson($data);
    }

    public function add()
    {
        $phone = $this->getParam('phone');
        $brand = $this->getParam('brand');
        $source_type = $this->getParam('source_type');
        if (!in_array($source_type, [1,2])) {
            $source_type = 1;
        }
        $this->getDb()->where('phone', $phone);
        $infos = $this->getDb()->get('infos');
        if (!empty($infos)) {
            $this->backJson([], ApiConst::BACK_INFO_PHONE_REPEAT);
        }
        $util = new BelongingToLocal();
        $address_phone = ($util->useTel($phone));
        $data = [
            'type'          => 0,
            'source'        => '',
            'source_type'   => $source_type,
            'state'         => 0,
            'phone'         => $phone,
            'search'        => '',
            'brand'         => $brand,
            'path'          => '',
            'ip'            => '',
            'address_ip'    => '',
            'address_phone' => $address_phone['res'] ? ($address_phone['area'] . "-" . $address_phone['city']) : '',
            'path_f'        => '',
            'created_at'    => time(),
            'u_id'          => $this->userInfo['id'],
            'u_pid'         => $this->userInfo['pid'],
            'update_at'     => time(),
        ];
        $res = $this->getDb()->insert('infos', $data);
        if ($res) {
            $this->backJson([]);
        }
        $this->backJson([], ApiConst::BACK_CODE_ERROR);
    }
}
